package com.han.nettytestdemo.connector.netty.hc;


import android.util.Log;

import com.han.nettytestdemo.connector.netty.intf.ConnectHCClientCallback;
import com.han.nettytestdemo.connector.netty.intf.MessageHcClientCallback;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


public class ClientHcHandler extends SimpleChannelInboundHandler<Object> {

    public static final String TAG = "ClientHandler";
    private NettyHCClient client;
    private MessageHcClientCallback messageClientCallback;
    private ConnectHCClientCallback connectCallback;

    public ClientHcHandler(NettyHCClient nettyClient,
                           ConnectHCClientCallback connectCallback) {
        this.client = nettyClient;
        this.connectCallback = connectCallback;

    }

    public void setMessageHcClientCallback(MessageHcClientCallback messageClientCallback) {
        this.messageClientCallback = messageClientCallback;
    }

    /**
     * 当收到数据的回调
     *
     * @param channelHandlerContext 封装的连接对像
     * @param o
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        Log.d(TAG, "客户端收到了数据：" + o.toString());
        if (null != messageClientCallback) {
            messageClientCallback.onHcClientCallback(o.toString());
        }
    }

    /**
     * 与服务端连接成功的回调
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Log.d(TAG, "与服务端连接成功：" + ctx.toString());
        if (null != connectCallback) {
            connectCallback.onHcConnect(0, "与服务端连接成功：" + ctx.toString());
        }
    }

    /**
     * 与服务端断开的回调
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        Log.d(TAG, "与服务端断开连接：" + ctx.toString());
        if (null != connectCallback) {
            connectCallback.onHcConnect(1, "与服务端断开连接：" + ctx.toString());
        }
        //启动重连
        reConnect(ctx);
    }

    /**
     * 5s重连一次服务端
     *
     * @param ctx
     */
    private void reConnect(final ChannelHandlerContext ctx) {
        EventLoop loop = ctx.channel().eventLoop();
        loop.schedule(() -> {
            Log.d(TAG, "连接断开，发起重连");
            if (null != connectCallback) {
                connectCallback.onHcConnect(1, "连接断开，发起重连：" + ctx.toString());
            }
            client.connectNetty();
        }, 5, TimeUnit.SECONDS);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                sendHeartPkg(ctx);
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 发送心跳
     */
    private void sendHeartPkg(ChannelHandlerContext ctx) {
//        ctx.channel().writeAndFlush("心跳数据包");
//        Log.d(TAG, "客户端发送心跳成功");
    }
}